#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022, Andrey Kunitsyn
#
# This file is part of the modm project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# -----------------------------------------------------------------------------

class Instance(Module):
    def __init__(self, instance):
        self.instance = instance

    def init(self, module):
        module.name = str(self.instance)
        module.description = "Instance {}".format(self.instance)

    def prepare(self, module, options):
        module.depends(":platform:i2c")
        return True

    def build(self, env):
        device = env[":target"]
        driver = device.get_driver("i2c")

        properties = device.properties
        properties["target"] = target = device.identifier
        properties["id"] = self.instance

        env.substitutions = properties
        env.outbasepath = "modm/src/modm/platform/i2c"

        env.template("i2c_master.hpp.in", "i2c_master_{}.hpp".format(self.instance))
        env.template("i2c_master.cpp.in", "i2c_master_{}.cpp".format(self.instance))
        env.template("i2c_master_impl.hpp.in", "i2c_master_impl_{}.hpp".format(self.instance))


def init(module):
    module.name = ":platform:i2c"
    module.description = "Inter-Integrated Circuit (I²C)"

def prepare(module, options):
    device = options[":target"]
    if not device.has_driver("i2c:rp20*"):
        return False

    module.depends(
        ":architecture:i2c",
        ":cmsis:device",
        ":platform:gpio")

    for instance in listify(device.get_driver("i2c")["instance"]):
        module.add_submodule(Instance(int(instance)))

    return True

def build(env):
    pass
